class TDCMWUtilsTagLib {

    static namespace = 'tdcmw'

    /**
     * This tag allows you to simply create ordered or unorder lists in HTML
     * easily. The list will be created as links if the controller and/or action
     * properties are provided.
     *
     * Options:
     *   ordered = Indicates if the list is ordered or not. Defaults to unordered.
     *   controller = The controller to use for the links if provided,
     *                defaults to the current controller if the action is provided.
     *   action = The action to use for the link if provided,
     *            defaults to show if controller is supplied.
     *   max = The maximum number of items to show from the list.
     *   sort = The sort order of the items if supplied. Valid values are asc
     *          and desc, if the value it not understood it is set to asc. The
     *          default is to display in the order received. Sorting is
     *          performed using the toString() method.
     *   list = The list to display.
     *   body = The body is the message to print if there are no list items.
     */
    def displayHTMLList = {attrs, body ->
        if (!attrs.list) {
            out << body() + "<br />"
            return
        }

        boolean ordered = false
        if (attrs.ordered == "true") {
            ordered = true
        }

        List list = attrs.list as List
        if (attrs.sort) {
            list.sort {i1, i2 ->
                if (attrs.sort == "desc") {
                    i2.toString() <=> i1.toString()
                } else {
                    i1.toString() <=> i2.toString()
                }
            }
        }

        if (attrs.max) {
            attrs.max = Integer.parseInt(attrs.max)
            if (list.size() > attrs.max && attrs.max > 0) {
                list = list[0..attrs.max - 1]
            }
        }

        if (ordered) {
            out << "<ol>"
        } else {
            out << "<ul>"
        }

        if (!attrs.controller && !attrs.action) {
            list.each {
                out << "<li>" + it.encodeAsHTML() + "</li>"
            }
        } else {
            def controller = attrs.controller?:controllerName
            def action = attrs.action?:'show'
            list.each {
                def text = it.encodeAsHTML()
                attrs.id = it.id
                out << "<li>" + g.link(controller:controller, action:action, id:it.id) {text} + "</li>"
            }
        }

        if (ordered) {
            out << "</ol>"
        } else {
            out << "</ul>"
        }
    }
}
